package org.dru.clay.respository.artifact;

import java.util.Arrays;
import java.util.StringTokenizer;

public class Version implements Comparable<Version> {
	private final String[] number;

	public Version(String... number) {
		this.number = number;
	}

	@Override
	public int compareTo(Version o) {
		if (o == null) {
			return 1;
		}
		for (int i = 0; i < number.length; i++) {
			if (i >= o.number.length) {
				return 1;
			}
			int ret = number[i].length() - o.number[i].length();
			if (ret != 0) {
				return ret;
			}
			ret = number[i].compareToIgnoreCase(o.number[i]);
			if (ret != 0) {
				return ret;
			}
		}
		return 0;
	}

	public String plain() {
		final StringBuilder builder = new StringBuilder();
		for (int i = 0; i < number.length; i++) {
			if (i > 0) {
				builder.append('.');
			}
			builder.append(number[i]);
		}
		return builder.toString();
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + Arrays.hashCode(number);
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Version other = (Version) obj;
		if (!Arrays.equals(number, other.number))
			return false;
		return true;
	}

	@Override
	public String toString() {
		return plain();
	}

	public static Version fromString(String versionString) throws IllegalArgumentException {
		try {
			final StringTokenizer tokenizer = new StringTokenizer(versionString, ".", false);
			final int count = tokenizer.countTokens();
			final String[] number = new String[count];

			for (int i = 0; i < count; i++) {
				number[i] = tokenizer.nextToken();
			}

			return new Version(number);
		} catch (NumberFormatException e) {
			throw new IllegalArgumentException("Invalid version string: " + versionString + " - " + e.getMessage());
		}
	}
}
